<template>
  <div class="container-app">
    <div style="margin-bottom:15px;">
      <el-button v-if="hasAdd" size="small" type="success" @click="addLine"><i class="el-icon-plus"></i>{{addTitle}}</el-button>
      <el-button v-if="hasDel" size="small" type="danger" @click="removeLine"><i class="el-icon-delete"></i>{{delTitle}}</el-button>
      <el-button v-if="hasUpdate" size="small" type="primary" @click="changeLine"><i class="el-icon-edit-outline"></i>{{updateTitle}}</el-button>
      <span class="right-search">
        <el-input @change="findLine" v-model="findData" size="small" placeholder="输入关键字搜索" style="width:300px;">
          <el-button @click="findLine" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </span>
    </div>
    <el-table @selection-change="getRow" :data="tableData" tooltip-effect="dark" style="width: 100%" border>
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="用户ID" width="80"></el-table-column>
      <el-table-column prop="username" label="登录账号"></el-table-column>
      <el-table-column prop="nickname" label="用户姓名"></el-table-column>
      <el-table-column prop="type" label="用户类型">
      	<template slot-scope="scope">
          <span v-if='scope.row.type ==1'>系统用户</span>
          <span v-else>普通用户</span>
        </template>
      </el-table-column>
      <el-table-column prop="roleName" label="角色"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <!--<el-table-column prop="email" label="Email"></el-table-column>-->
      <el-table-column prop="departmentName" label="所属部门"></el-table-column>
      <el-table-column prop="createName" label="创建人"></el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="120"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="success" size="mini" @click="restRolePwd(scope.row)"><i class="el-icon-check"></i> 重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-col :span="24" class="paging">
      <span>总条数：{{dataTotal}}</span>
      <el-pagination @current-change="changePage" :page-size="10" :total="dataTotal"
        background layout="prev, pager, next"
        style="float:right;"></el-pagination>
		</el-col>

    <!--对话界面-->
		<el-dialog :title="title" :visible="roleVisible" width="50%" :before-close="handleClose" :close-on-click-modal='false'>
      <el-form size="small" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="form-submit">
        <el-form-item label="用户类型">
          <el-radio-group v-model="isType" @change="changeType">
            <el-radio :label="1">系统用户</el-radio>
            <el-radio :label="2">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="登录账号" prop="username">
          <el-input :disabled="!changeVisible" size="small" v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" v-show="changeVisible">
          <span style="color:#f56c6c">初始密码默认为 “123456”</span>
        </el-form-item>
        <el-form-item label="用户姓名" prop="nickname">
          <el-input size="small" v-model="ruleForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input size="small" v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <!--<el-form-item label="电子邮箱" prop="email">
          <el-input size="small" v-model="ruleForm.email"></el-input>
        </el-form-item>-->
        <el-form-item label="权限角色" prop="roleId">
          <el-select @change="choRole" style="width:100%" size="small" v-model="ruleForm.roleId" filterable placeholder="请选择">
            <el-option v-for="item in roles" :key="item.id"
              :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentId">
          <el-select @change="choDept" style="width:100%" size="small" v-model="ruleForm.departmentId" placeholder="请选择">
            <el-option v-for="item in departments" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否可用" v-show="!changeVisible">
          <el-radio-group v-model="isUsable">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
          <div style="color:#f56c6c">注意：选择“否”，即不可用是删除当前用户</div>
        </el-form-item>
      </el-form>
      <span slot="footer" style="padding-right:30px;">
        <el-button size="small" type="success" @click="submitForm('ruleForm')">保存</el-button>
        <el-button v-show="changeVisible" size="small" type="warning" @click="resetForm('ruleForm')">重置</el-button>
        <el-button size="small" @click="cancleForm('ruleForm')">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { isvalidatemobile } from '@/utils/validate'
import {
  getUserList,
  addUser,
  removeUser,
  getRoleInfo,
  getDepartment,
  restUserPwd,
  queryRepetition,
  updateUser } from '@/api/userTable'
export default {
  data() {
    const validateLoginName = (rule, value, callback) => {
      if (this.isAdd) {
        const para = { username: value }
        queryRepetition(para).then(res => {
          if (res.code == '200') {
            callback()
          } else {
            callback(new Error(res.message))
          }
        })
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (isvalidatemobile(value)[0]) {
        callback(new Error(isvalidatemobile(value)[1]))
      } else {
        callback()
      }
    }
    return {
      title: '新增用户',
      roleVisible: false,
      isUsable: 1,
      isType: 1,
      changeVisible: true,
      userData: [],
      dataPage: 1,
      dataTotal: 1,
      tableData: [],
      ruleForm: {
        nickname: '',
        username: '',
        phone: '',
        email: '',
        departmentId: '',
        password: '',
        roleId: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: validateLoginName }
        ],
        nickname: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: validatePhone }
        ],
        /* email: [
          { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          { type: 'email', message: '请正确输入电子邮箱', trigger: 'blur' }
        ],*/
        roleId: [
          { required: true, message: '请选择权限角色', trigger: 'change' }
        ],
        departmentId: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ]
      },
      roles: [],
      departments: [],
      removeIds: [],
      isAdd: true,
      userId: '',
      departmentId: 1,
      roleId: 38,
      findData: '',
      hasAdd: false,
      hasDel: false,
      hasUpdate: false,
      addTitle: '新增',
      updateTitle: '修改',
      delTitle: '删除'
    }
  },
  mounted() {
    this.getUserList()
    this.getRoleDept()
    this.getJur()
  },
  methods: {
    getJur() {
      const self = this
      self.$store.dispatch('Juage', self.$store.clickMenuId).then(res => {
        if (res.code == '200') {
          res.data.forEach(item => {
            if (item.type == '3') {
              self.hasAdd = true
              self.addTitle = item.title
            }
            if (item.type == '5') {
              self.hasDel = true
              self.delTitle = item.title
            }
            if (item.type == '4') {
              self.hasUpdate = true
              self.updateTitle = item.title
            }
          })
        } else if (res.code !== '507') {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    // 获取用户列表
    getUserList() {
      const para = { pageIndex: this.dataPage, pageSize: 10 }
      getUserList(para).then(res => {
        if (res.code == '200') {
          this.dataTotal = res.data.total
          this.tableData = res.data.records
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    // 获取部门列表、权限角色
    getRoleDept() {
      getDepartment().then(res => {
        if (res.code == '200') {
          this.departments = res.data
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
      getRoleInfo().then(res => {
        if (res.code == '200') {
          this.roles = res.data
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    changePage(val) {
      this.dataPage = val
      this.getUserList()
    },
    changeType(val) {
    	this.isType = val
    },
    restRolePwd(row) {
      this.$confirm('是否重置用户' + row.username + '的登录密码为123456?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const para = {
          id: row.id,
          newPassword: '123456'// 'e10adc3949ba59abbe56e057f20f883e'
        }
        restUserPwd(para).then(res => {
          if (res.code == '200') {
            this.$message({
              type: 'success',
              message: res.message
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    handleClose() {
      this.roleVisible = false
    },
    submitForm(formName) {
      const self = this
      self.$refs[formName].validate((valid) => {
        if (valid) {
          const para = {
            nickname: self.ruleForm.nickname,
            username: self.ruleForm.username,
            phone: self.ruleForm.phone,
            email: self.ruleForm.email,
            type: self.isType
          }
          if (self.isAdd) {
            para.roleId = self.ruleForm.roleId
            para.departmentId = self.ruleForm.departmentId
            para.password = '123456'// 'e10adc3949ba59abbe56e057f20f883e'
            para.state = 1
            addUser(para).then(res => {
              if (res.code == '200') {
                this.$message({
                  type: 'success',
                  message: res.message
                })
                this.getUserList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
              self.roleVisible = false
              this.$refs[formName].resetFields()
            })
          } else {
            para.roleId = self.roleId
            para.departmentId = self.departmentId
            para.id = parseInt(self.userId)
            para.state = self.isUsable
            updateUser(para).then(res => {
              if (res.code == '200') {
                this.$message({
                  type: 'success',
                  message: res.message
                })
                this.getUserList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
              self.roleVisible = false
              this.$refs[formName].resetFields()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.restData()
    },
    cancleForm(formName) {
      this.$refs[formName].resetFields()
      this.roleVisible = false
    },
    removeLine() {
      if (this.userData.length) {
        this.$confirm('删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const para = { ids: this.removeIds.toString() }
          removeUser(para).then(res => {
            if (res.code == '200') {
              this.$message({
                type: 'success',
                message: res.message
              })
              this.getUserList()
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.$message('请先选择需要删除的用户！')
      }
    },
    restData() {
      this.ruleForm.nickname = ''
      this.ruleForm.username = ''
      this.ruleForm.phone = ''
      this.ruleForm.email = ''
      this.ruleForm.roleId = ''
      this.ruleForm.departmentId = ''
    },
    addLine(formName) {
      this.title = '新增用户'
      this.roleVisible = true
      this.changeVisible = true
      self.isAdd = true
      this.restData()
    },
    changeLine() {
      const self = this
      if (self.userData.length && self.userData.length === 1) {
        self.isAdd = false
        self.title = '修改用户'
        self.roleVisible = true
        self.changeVisible = false
        self.ruleForm.nickname = self.userData[0].nickname
        self.ruleForm.username = self.userData[0].username
        self.ruleForm.phone = self.userData[0].phone
        self.ruleForm.email = self.userData[0].email
        self.ruleForm.roleId = self.userData[0].roleName
        self.ruleForm.departmentId = self.userData[0].departmentName
        self.isType = parseInt(self.userData[0].type)
        self.userId = self.userData[0].id
        self.isUsable = self.userData[0].state
        self.roles.forEach(item => {
          if (item.name === self.userData[0].roleName) {
            self.roleId = item.id
          }
        })
        self.departments.forEach(item => {
          if (item.name === self.userData[0].departmentName) {
            self.departmentId = item.id
          }
        })
      } else {
        this.$message('请选择一个用户进行修改！')
      }
    },
    getRow(selection) {
      this.removeIds = []
      this.userData = selection
      selection.forEach(item => {
        this.removeIds.push(item.id)
      })
    },
    findLine() {
      const para = { row: 10, page: 1, keywords: this.findData }
      getUserList(para).then(res => {
        if (res.code == '200') {
          this.dataTotal = res.datas.total
          this.tableData = res.datas.list
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    choRole() {
      this.roleId = this.ruleForm.roleId
    },
    choDept() {
      this.departmentId = this.ruleForm.departmentId
    }
  }
}
</script>

<style scoped>
.paging{
  padding: 15px;
  padding-right: 0;
}
.form-submit{
  margin: 0;
  padding-right: 30px;
}
</style>
